<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>concatImage</title>
</head>

<body>
    <img src="../concatImages/img1.png" alt="图片加载中" id="testImage">
    <script>
        const concatImage = (data, callback, options = { width: 300, height: 300, fillStyle: "#fff", type: "image/jpg", encoderOptions: .9 }) => {
            const { width, height, fillStyle, type, encoderOptions } = options;
            const can = document.createElement('canvas'),
                ctx = can.getContext('2d'),
                len = data.length,
                res = [],
                createImg = (count) => {
                    if (len > count) {
                        const img = new Image();
                        img.src = data[count];
                        img.onload = () => {
                            ctx.drawImage(img, 0, 0, width, height);
                            createImg(count + 1);
                        }
                    } else {
                        res.push(can.toDataURL(type, encoderOptions));
                        callback?.(res);
                    }
                }
            can.width = width;
            can.height = height;
            ctx.rect(0, 0, can.width, can.height);
            ctx.fillStyle = fillStyle;
            ctx.fill();
            createImg(0);
        };
        const imgEl = document.querySelector('#testImage');
        concatImage(['../concatImages/img1.png', '../concatImages/img2.png', '../concatImages/img3.png', '../concatImages/img4.png'], (res) => {
            console.log(res);
            imgEl.setAttribute('src', res[0])
        })
    </script>
</body>

</html>